package com.xy.biz.base.service.impl;

import com.xy.biz.base.manager.DictManager;
import com.xy.lang.domain.treeing.TreeItem;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Greekn Zhang
 * @date 2021/7/23 15:45
 * @description
 */
@Component
public class DictInitialize implements InitializingBean {
    @Autowired
    private DictManager dictManager;
    @Autowired
    private DictInitializeEventBus dictInitializeEventBus;

    private final static Map<String, String> map = new HashMap<>();

    @PostConstruct
    public void initialize() {
        List<TreeItem> treeItems = dictManager.listDictGroupItemAll(1);
        buildMap(treeItems);
    }

    public void buildMap(List<TreeItem> treeItems) {
        if (!CollectionUtils.isEmpty(treeItems)) {
            treeItems.stream().peek(t -> {
                map.put(t.getLabel(), t.getValue());
                if (!CollectionUtils.isEmpty(t.getChildren())) {
                    buildMap(t.getChildren());
                }
            }).collect(Collectors.toList());
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        dictInitializeEventBus.addHandle((id) -> {
            List<TreeItem> treeItems = dictManager.listDictGroupItemAll(1);
            buildMap(treeItems);
        });
    }

    public String getValue(String code) {
        if (map.containsKey(code)) {
            return map.get(code);
        }
        return null;
    }
}
